package com.ruoyi.recycle.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.recycle.domain.ClientCoupon;
import com.ruoyi.recycle.domain.Coupon;
import com.ruoyi.recycle.domain.CouponStock;
import com.ruoyi.recycle.mapper.ClientCouponMapper;
import com.ruoyi.recycle.mapper.CouponMapper;
import com.ruoyi.recycle.mapper.CouponStockMapper;
import com.ruoyi.recycle.service.CouponService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    @Resource
    private CouponStockMapper couponStockMapper;
    @Resource
    private ClientCouponMapper clientCouponMapper;

    @Override
    public AjaxResult clientGetCoupon(Integer clientId, String couponId) {

        Integer flag = clientCouponMapper.selectCount(new LambdaQueryWrapper<ClientCoupon>().
                eq(ClientCoupon::getClientId, clientId).
                eq(ClientCoupon::getCouponNo, couponId).
                ne(ClientCoupon::getStatus,"已使用"));

        if (flag>0){
            return AjaxResult.error("您已领取该优惠券，请先使用后再领取");
        }
        List<CouponStock> stockList = couponStockMapper.selectList(new LambdaQueryWrapper<CouponStock>().eq(CouponStock::getCouponId, couponId).ne(CouponStock::getStatus, "已领取"));
        if (CollUtil.isNotEmpty(stockList) && stockList.size()<1){
            return AjaxResult.error("很抱歉，该优惠券已经被领完了，请领取别的优惠券吧");
        }
        CouponStock couponStock = stockList.get(0);
        couponStock.setStatus("已领取");
        couponStockMapper.updateById(couponStock);

        ClientCoupon clientCoupon = new ClientCoupon();

        clientCoupon.setCouponNo(couponStock.getCouponNo());
        clientCoupon.setClientId(clientId);
        clientCoupon.setAmount(1);
        clientCoupon.setCreateTime(new Date());
        clientCoupon.setStatus("未使用");
        clientCouponMapper.insert(clientCoupon);

        return AjaxResult.success();
    }
}
